
$(function () {

    function roomTbody(list) {
        var str = '';
        for(var i=0; i<list.length; i++){
            str+='<tr data-id='+list[i].id +' data-token='+ list[i].token +'>' +
                '<td>'+list[i].title+'</td>' +
                '<td>'+(new Date(list[i].createTime)).format("yyyy-MM-dd hh:mm:ss")+'</td>' +
                '<td>'+list[i].ownerName+'</td>' +
                '<td>'+roomStatus(list[i].status)+'</td>' +
                '<td>'+(list[i].type == "1" ? "普通":"娱乐")+'</td>' +
                // '<td><a class="upDataVideo">上传</a></td>' +
                '<td><a class="roomedit">编辑</a>'+(list[i].type == "1" ? "" : ' | <a href="#/room-page/' + list[i].id + '" >操作</a>') +'</td>' +
                '</tr>'
        }

        return str
    }
    function roomStatus(status) {
        if(status == "0"){
            return '正常'
        }

        if(status == "-1"){
            return '关闭中'
        }

        if(status == "-2"){
            return '停用'
        }
    }



    function layerRoomSet(owners,opts) {
        return '<div style="padding: 10px 0"> ' +
            '<div class="form-group">' +
            '<label class="col-sm-3 control-label">状态:<span class="asterisk">*</span></label>' +
            '<div class="col-sm-7">' +
            '<select class="form-control room-status" >' +(function (status) {
                var str="";
                    var _roomStatus=[
                        {val:"0",text:"正常"},
                        {val:"-1",text:"关闭中"},
                        {val:"-2",text:"停用"}
                    ];

                for(var i=0; i< _roomStatus.length; i++ ){
                    str+= '<option value="'+ _roomStatus[i].val +'" >'+  _roomStatus[i].text +'</option>'
                }

                    return str

            })(opts.status) +'</select>' +
            '<div class="error alert alert-danger" ><strong></strong></div></div>' +
            '</div>' +(window.localStorage.getItem('role') !=3 ? function () {

                return '<div class="form-group">' +
                '<label class="col-sm-3 control-owner">管理者:<span class="asterisk">*</span></label>' +
                '<div class="col-sm-7">' +
                '<select class="form-control room-owner" >' +(function (owners) {
                    var str="";


                    for(var i=0; i< owners.length; i++ ){
                        str+= '<option value="'+ owners[i].id +'" >'+  owners[i].userName +'</option>'

                    }

                    return str

                })(owners) +'</select>' +
                '<div class="error alert alert-danger" ><strong></strong></div></div>' +
                '</div>'
            }():"") +



            '<div class="form-group">' +
            '<label class="col-sm-3 control-label">房间类型:<span class="asterisk">*</span></label>' +
            '<div class="col-sm-7">' +
            '<select class="form-control room-type" >' +
            '<option value="1">普通聊天室</option>' +
            '<option value="2">娱乐聊天室</option>' +
            '</select>' +
            '<div class="error alert alert-danger" ><strong></strong></div></div>' +
            '</div>' +
            '<div class="form-group">' +
            '<label class="col-sm-3 control-label">名称:<span class="asterisk">*</span></label>' +
            '<div class="col-sm-7"><input type="text" value="'+opts.title+'" class="room-title form-control"><div class="error alert alert-danger" ><strong></strong></div></div>' +
            '</div>' +
            '<div class="form-group">' +
            '<label class="col-sm-3 control-label">信息:<span class="asterisk">*</span></label>' +
            '<div class="col-sm-7"><textarea class="room-info form-control">'+opts.info+'</textarea><div class="error alert alert-danger" ><strong></strong></div></div>' +
            '</div>' +
            '</div>'
    }
    function queryDatum() {
        pageInit({
            pageNum: 1,
            pageSize:10,
            token: window.localStorage.getItem('token'),
            title: $("#room-title").val() || "",
            ownerName: $("#room-ownerName").val() || "",
        });
    }

    function resetDatum (){
        pageInit({
            pageNum: 1,
            pageSize:10,
            token: window.localStorage.getItem('token')
        });
    }


    function pageInit(requestData) {
        var pageInit_layer = layer.load(0);
        $.restPost('/room/doPageQuery',requestData).done(function (msg,data) {
            layer.close(pageInit_layer)
            // console.log(msg,data)



            $("#room-table tbody").html(roomTbody(data.list))

            $(".roomedit").off("click").on("click",function () {
                var _id = $(this).parents('tr').attr('data-id')
                var roomedit_layer = layer.load(0);
                $.when($.restPost('/room/doSelect',{
                    token:window.localStorage.getItem('token'),
                    id: _id
                }),$.restPost('/user/doQuery',{
                    token:window.localStorage.getItem('token'),
                    role:3
                })).done(function (res1,res2) {
                    layer.close(roomedit_layer)
                    // console.log(res1[1],res2[1])
                    $.rootOpenDialog({
                        title: "房间设置",
                        btn: ["提交"],
                        content: layerRoomSet(res2[1].list,{
                            title:res1[1].title,
                            info:res1[1].info
                        }),
                        success:function (lay) {
                            // console.log($(lay).find(".room-owner"),res1[1].owner)
                            $(lay).find(".room-owner").val(res1[1].owner)
                            $(lay).find(".room-status").val(res1[1].status)
                            $(lay).find(".room-type").val(res1[1].type)
                        },
                        yes: function (index,lay) {
                            var $lay = $(lay)
                            var roomedit_layer1 = layer.load(0);
                            $.restPost('/room/doUpdate', {
                                token:window.localStorage.getItem('token'),
                                id: _id,
                                title:$lay.find(".room-title").val(),
                                info:$lay.find(".room-info").val(),
                                status:$lay.find(".room-status").val(),
                                owner:window.localStorage.getItem('role') !=3?$lay.find(".room-owner").val():window.localStorage.getItem('userId'),
                                type:$lay.find(".room-type").val(),

                            }).done(function (msg, data) {
                                layer.close(roomedit_layer1)
                                layer.close(index)
                                $.rootSuccessDialog("修改成功",2000)
                                pageInit(requestData);
                            }).fail(function (msg) {
                                layer.close(roomedit_layer1)
                                $.rootErrorDialog("修改失败",2000)
                            })

                        }


                    });
                })

            });

            $("#addRoom").off("click").on("click",function () {
                var addRoom_layer = layer.load(0);
                $.restPost('/user/doQuery',{
                    token:window.localStorage.getItem('token'),
                    role:3
                }).done(function (msg,data) {
                    layer.close(addRoom_layer)
                    $.rootOpenDialog({
                        title: "新增房间",
                        btn: ["提交"],
                        content: layerRoomSet(data.list,{
                            title:"",
                            info:""
                        }),
                        yes: function (index,lay) {
                            var $lay = $(lay)
                            // console.log($lay.find(".room-title").val())
                            var addRoom_layer1 = layer.load(0);
                            $.restPost('/room/doInsert', {
                                token:window.localStorage.getItem('token'),
                                title:$lay.find(".room-title").val(),
                                info:$lay.find(".room-info").val(),
                                status:$lay.find(".room-status").val(),
                                owner:window.localStorage.getItem('role') !=3?$lay.find(".room-owner").val():window.localStorage.getItem('userId'),
                                type:$lay.find(".room-type").val(),

                            }).done(function (msg, data) {
                                layer.close(addRoom_layer1)
                                layer.close(index)
                                $.rootSuccessDialog("新增成功",2000)
                                pageInit(requestData);
                            }).fail(function (msg) {
                                layer.close(addRoom_layer1)
                                $.rootErrorDialog("新增失败",2000)
                            })

                        }


                    });
                }).fail(function (msg) {
                    layer.close(addRoom_layer)
                    $.rootErrorDialog("用户请求失败重新操作",2000)
                })

            })

           /* $(".upDataVideo").off("click").on("click",function () {
                $.rootOpenDialog({
                    title: "新增房间",
                    btn: ["提交"],
                    content: '<div style="padding: 10px">' +
                    '<div class="room-video button">上传</div>' +
                    '</div>',
                    success:function () {
                        var roomVideo = WebUploader.create({

                            // 选完文件后，是否自动上传。
                            auto: false,

                            // swf文件路径
                            swf: '/js/Uploader.swf',

                            // 文件接收服务端。
                            server: '/file/upload',
                            fileNumLimit: 2,
                            duplicate:true,
                            // 选择文件的按钮。可选。
                            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                            pick: '.room-video',
                            accept: {
                                title: '视频上传',
                                extensions: '3gp,mp4,rmvb,mov,avi,m4v',
                                mimeTypes: 'video/!*,audio/!*,application/!*',
                            }
                        });
                        roomVideo.on( 'fileQueued', function( file ) {
                            alert(11)
                        });
                        roomVideo.on( 'uploadSuccess', function( file ,response) {
                            if(response.code == 1){

                            }

                            alert(22)


                        });
                        roomVideo.on( 'uploadError', function( file ) {
                            alert(333)
                        });

                    },
                    yes: function (index,lay) {
                        var $lay = $(lay)


                    }


                });
            });*/

            $("#queryDatum").off("click").on("click", function () {
                queryDatum()
            });

            $("#resetDatum").off("click").on("click", function () {
                resetDatum()
            });

            laypage({
                cont: 'page', //容器。
                pages: data.pages, //通过后台拿到的总页数
                curr: requestData.pageNum || 1, //当前页
                skip: true, //是否开启跳页
                skin: 'molv', //皮肤,
                jump: function (obj, first) { //触发分页后的回调
                    requestData.pageNum = obj.curr;
                    if (!first) { //点击跳页触发函数自身，并传递当前页：obj.curr
                        pageInit(requestData);
                    }
                }
            });


        })
    }

    pageInit({
        pageNum: 1,
        pageSize:10,
        token: window.localStorage.getItem('token')
    })
})

